<template>
  <div class="page-container">
    <page-form :model="form" layout="vertical" div="true" class="page-form" ref="formRef">
      <page-form-row>
        <page-form-item field="role" label="角色名称" size="1/3" :rules="{ message: '请输入角色名称', required: true }">
          <i-input placeholder="请输入" :max-length="20" v-model="form.role" />
        </page-form-item>
        <page-form-item field="description" label="备注" size="2/3">
          <i-input placeholder="请输入" :max-length="200" allow-clear v-model="form.description" auto-size />
        </page-form-item>
      </page-form-row>
      <page-form-row>
        <page-form-item size="1">
          <div class="arco-form-item-label" style="margin-right: 16px">配置</div>
          <a-button type="primary" size="mini" @click="useRole">使用其他角色配置</a-button>
          <a-tooltip content="将其他角色的功能权限引入到当前角色">
            <icon-question-circle style="font-size: 16px; margin-left: 6px; color: #4e5969" />
          </a-tooltip>
        </page-form-item>
      </page-form-row>
      <page-form-row :gutter="50">
        <page-form-item size="1/3">
          <permissionTable
            ref="PcTableRef"
            :id="form.id"
            @checkChange="treeChangedCode"
            :title="'PC端后台权限'"
            :index="0"
            :isEdit="isEdit"
          />
        </page-form-item>
        <page-form-item style="margin-left: 19px" size="1/3">
          <permissionTable
            ref="AppTableRef"
            :id="form.id"
            @checkChange="treeAppChangedCode"
            :title="'APP端后台权限'"
            :index="1"
            :isEdit="isEdit"
          />
        </page-form-item>
      </page-form-row>
    </page-form>
    <a-modal
      class="copyModal"
      title="复制其他角色配置"
      v-model:visible="roleVisible"
      :on-before-ok="handleRoleOk"
      @cancel="handleRoleCancel"
    >
      <page-form-item label="角色名称" size="1">
        <!-- popup-container=".copyModal" -->
        <a-select placeholder="请输入" v-model="selectedRole" @change="changeRole">
          <a-option v-for="item in allRoleList" :key="item.id" :value="item.id" :label="item.role" />
        </a-select>
      </page-form-item>
    </a-modal>
  </div>
  <page-form-footer :ok-loading="okLoading" @ok="saveRoleForm" />
</template>

<script setup name="MerchantRoleForm">
  import { ref, onMounted } from 'vue'
  import { roleCreate, roleUpdate, getEpList } from '@/api/merchant/role'
  import { useRoute } from 'vue-router'
  import { Modal, Message } from '@arco-design/web-vue'
  import permissionTable from '../components/permissionTable.vue'
  import useNavigate from '@/hooks/useNavigate'
  const { navigateBack } = useNavigate()

  const roleVisible = ref(false)
  const formRef = ref() // 表单校验
  const isEdit = ref(false)
  const route = useRoute()
  const PcTableRef = ref(null)
  const AppTableRef = ref(null)

  const checkedRoleId = ref({})
  const selectedRole = ref()
  const allRoleList = ref([])
  const changeRole = (val) => {
    checkedRoleId.value = val
  }
  const getRoleData = () => {
    getEpList().then((res) => {
      if (isEdit.value) {
        allRoleList.value = res.result.filter((i) => {
          return i.id != route.params.id
        })
      } else {
        allRoleList.value = res.result
      }
    })
  }

  const form = ref({
    role: route.query.role || '',
    description: route.query.description,
    id: route.params.id || '',
  })
  const pcChanged = ref('')
  const appChanged = ref('')
  // const changeList = [{ title: 'PC端后台权限' }, { title: '移动端后台权限' }]

  const treeChangedCode = (val) => {
    pcChanged.value = val
  }
  const treeAppChangedCode = (val) => {
    appChanged.value = val
  }

  const handleRoleOk = async () => {
    if (selectedRole.value) {
      Modal.confirm({
        title: '提示',
        cancelText: '取消',
        okText: '确认',
        bodyStyle: {
          'text-align': 'center',
        },
        content: '请确认是否使用已选角色的配置？当前角色的功能权限将会被覆盖',
        onOk: () => {
          roleVisible.value = false
          form.value.id = checkedRoleId.value
          selectedRole.value = ''
          PcTableRef.value.getRoleList(form.value.id)
          AppTableRef.value.getRoleList(form.value.id)
          return true
        },
      })
    } else {
      Message.error('请选择角色')
      return false
    }
  }
  const handleRoleCancel = () => {
    roleVisible.value = false
  }

  // 确认
  const okLoading = ref(false)
  const saveRoleForm = () => {
    if (!form.value.role) {
      Message.error('请选择角色名称')
    } else {
      form.value.id = route.name == 'MerchantRoleForm_Create' ? '' : route.params.id || ''
      const totalList = pcChanged.value.concat(appChanged.value)
      form.value.resourceIds = totalList.join(',')
      okLoading.value = true

      if (isEdit.value) {
        Modal.confirm({
          title: '提示',
          simple: true,
          cancelText: '关闭',
          okText: '确认',
          content: '编辑角色后，请尽快联系相关员工重新登录系统，保证权限准确性',
          onOk: () => {
            roleUpdate(form.value)
              .then((res) => {
                console.log(res, '编辑测试')
                Message.success(res.message)
                navigateBack()
                okLoading.value = false
              })
              .catch(() => {
                okLoading.value = false
              })
          },
          onCancel: () => {
            okLoading.value = false
          },
        })
      } else {
        roleCreate(form.value)
          .then((res) => {
            console.log(res, '新增测试')
            Message.success(res.message)
            navigateBack()
            okLoading.value = false
          })
          .catch(() => {
            okLoading.value = false
          })
      }
    }
  }
  const useRole = () => {
    roleVisible.value = true
  }
  onMounted(() => {
    getRoleData()
    isEdit.value = route.name == 'MerchantRoleForm_Edit' ? true : false
  })
</script>
<style lang="less" scoped>
  .copyModal {
    position: relative;
  }
  .fx {
    display: flex;
    justify-content: space-between;
  }
</style>
